/**
 *       Copyright (c) 2012 Lukas Zaruba
 *
 *   This file is part of Robot Playground.
 *
 *   Robot Playground is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Robot Playground is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with Robot Playground. If not, see <http://www.gnu.org/licenses/>.
 */
package net.zarubsys.robotplayground.core.program;

import net.zarubsys.robotplayground.core.Environment;

import org.apache.log4j.MDC;

/**
 * ProgramRunnable
 *
 * @author Lukas Zaruba, lukas.zaruba@gmail.com
 */
public class ProgramRunnable implements Runnable {
	
	private final IProgram<IProgramConfiguration> program;
	private final API api;
	private final IProgramConfiguration configuration;
	private final Environment env;
	private IProgramFinishedListenerInternal finishedListener;
	private boolean finished = false;
	
	public ProgramRunnable(IProgram<IProgramConfiguration> program, API api, IProgramConfiguration configuration, 
			Environment env) {
		this.program = program;
		this.api = api;
		this.configuration = configuration;
		this.env = env;
	}
	
	public void addFinishedListener(IProgramFinishedListenerInternal finishedListener) {
		this.finishedListener = finishedListener;
	}

	@Override
	public void run() {
		MDC.put(Environment.LOG_PATH_KEX, env.getLogPath());
		try {
			program.run(api, configuration, env);
		} catch (Exception e) {
			env.getLogger().error("Erorr while executing program " + program + "!");
		} finally {
			finished = true;
			if (finishedListener != null) finishedListener.notifyFinished(program);
		}
	}
	
	public IProgram<IProgramConfiguration> getProgram() {
		return program;
	}
	
	public boolean finished() {
		return finished;
	}

}

